<?php
session_start();

$_SESSION["errmsg"] = '';
$url = $_SERVER['HTTP_REFERER'];
require_once '../include/config.lib.php';
require_once '../include/database.lib.php';

if($_SESSION["personid"] == null)
{
	$_SESSION["previouspage"] = $url;
	$_SESSION["errmsg"] = "Please log in first.";
	echo "<HTML><META http-equiv=\"refresh\" content=\"0; url=../login.php\"></HTML>";//redirect to the login page
}

else 
{
	// Connect to the DB.
	ConnectToDB();
	//$selectReq = "SELECT * FROM DB2INST1.watchlist WHERE PERSONID = ".$_SESSION['personid']." AND RESOURCEID = ".$_SESSION['paperid']."";
	$selectResult = DBExecute("SELECT * FROM watchlist WHERE PERSONID = ? AND RESOURCEID = ?", array($_SESSION['personid'],$_SESSION['paperid']));
	$select = $selectResult->fetchAssocRow();
	if($select != null)
	{
	?>
		<script>
			alert("This paper has already been in your watch list!");
		</script>
		<?php
		echo "<HTML><META http-equiv=\"refresh\" content=\"0; url='".$url."'\"></HTML>";//redirect to the home page	
	}
	else 
	{
		//$req = "INSERT INTO DB2INST1.watchlist (PERSONID, RESOURCEID) VALUES(".$_SESSION['personid'].", ".$_SESSION['paperid'].")";
		echo $_SESSION["personid"]." ".$_SESSION["paperid"]."<br/>";
		$watchlistReq = DBExecute("INSERT INTO watchlist (PERSONID, RESOURCEID) VALUES(?, ?)", array($_SESSION["personid"],$_SESSION["paperid"]));
		if($watchlistReq)
		{
			?>
			<script>
				alert("This topic has been inserted successfully into your watch list.");
			</script>
			<?php 
			echo "<HTML><META http-equiv=\"refresh\" content=\"0; url='".$url."'\"></HTML>";//redirect to the home page
		}
		else
		{
		?>
			<script>
				alert("Internal Error!");
			</script>
			<?php
			echo "<HTML><META http-equiv=\"refresh\" content=\"0; url='".$url."'\"></HTML>";//redirect to the home page
		}
	}
}

?>